package cn.tedu.boyou.acticle.service.impl;

import cn.tedu.boyou.acticle.domain.DestTheme;
import cn.tedu.boyou.acticle.mapper.DestThemeMapper;
import cn.tedu.boyou.acticle.service.IDestThemeService;
import cn.tedu.boyou.common.query.DestThemeQuery;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * 目的地主题服务实现类
 */
@Service
public class DestThemeServiceImpl implements IDestThemeService{

    @Autowired
    private DestThemeMapper destThemeMapper;

    @Override
    public List<DestTheme> listTopTheme(int num) {
        return destThemeMapper.selectTopThemeOrdered(num);
    }

    @Override
    public List<DestTheme> getSubthemesByThemeId(Long themeId) {
        return destThemeMapper.selectByParentId(themeId);
    }

    @Override
    public List<DestTheme> listSubTheme() {

        int deep = 2;

        return destThemeMapper.selectByDeep(deep);
    }

    @Override
    public PageInfo<DestTheme> query(DestThemeQuery qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        return new PageInfo<>(destThemeMapper.selectByParentId(qo.getParentId()));
    }

    @Override
    public DestTheme getByPrimaryKey(Long id){
        return destThemeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<DestTheme> getToasts(DestThemeQuery qo) {
        ArrayList<DestTheme> list = new ArrayList<>();
        this.creatToasts(list,qo.getParentId());
        Collections.reverse(list);
        return list;
    }

    @Override
    public void saveOrUpdate(DestTheme destTheme) {
        if (destTheme.getId() == null){
            destThemeMapper.insert(destTheme);
        }else {
            destThemeMapper.updateByPrimaryKey(destTheme);
        }
    }

    private void creatToasts(List list, Long parentId) {
        DestTheme theme = destThemeMapper.selectByPrimaryKey(parentId);
        if (theme != null){
            list.add(theme);
            if (theme.getParentTheme() == null)
                return;
            this.creatToasts(list,theme.getParentTheme().getId());
        }
    }

    @Override
    public List<DestTheme> listThemesByDeep(int deep) {
        return destThemeMapper.selectByDeep(deep);
    }

    @Override
    public List<Map<DestTheme, List<DestTheme>>> listTopThemesWithSubThemes(int num) {

        List<DestTheme> topThemes = listTopTheme(num);

        ArrayList<Map<DestTheme,List<DestTheme>>> list = new ArrayList<>();

        for (DestTheme topTheme : topThemes) {
            HashMap<DestTheme, List<DestTheme>> map = new HashMap<>();
            List<DestTheme> subThemes = getSubthemesByThemeId(topTheme.getId());
            map.put(topTheme,subThemes);
            list.add(map);
        }
        return list;
    }
}
